package com.wondersgroup.robot.web.action;

import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.hibernate.Transaction;
import org.mira.lucene.analysis.IK_CAnalyzer;

import com.wondersgroup.robot.dao.RoKeyDAO;
import com.wondersgroup.robot.dao.RoQuestionKeyDAO;
import com.wondersgroup.robot.po.RoKey;
import com.wondersgroup.robot.po.RoQuestionKey;
import com.wondersgroup.robot.po.RoQuestionKeyId;

public class SplitQuestion implements Runnable{
	private String roquId;
	private String question;
	private String answer;
	public SplitQuestion(String roquId, String question, String answer){
		this.roquId = roquId;
		this.question = question;
		this.answer = answer;
		
	}
	public void run() {
		
		try {
			List list = splitWord(this.question);
			this.saveKey(list);
			list = splitWord(this.answer);
			this.saveKey(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
    public List splitWord(String sentence) throws Exception {
    	List list = new ArrayList();
		if (StringUtils.isNotEmpty(sentence)) {
			sentence = sentence.replaceAll("<[^>]*>|&[^;]*;", "");
			Analyzer analyzer = new IK_CAnalyzer();
			Reader r = new StringReader(sentence);
			TokenStream ts = (TokenStream) analyzer.tokenStream("", r);
			Token t;
			while ((t = ts.next()) != null) {
				list.add(t.termText());
			}
		}
		return list;
	}
    private void saveKey(List list){
		RoKeyDAO rkd = new RoKeyDAO();
		RoQuestionKeyDAO rqkd = new RoQuestionKeyDAO();
		RoKey rk = null;
		RoQuestionKey rqk = null;
		Transaction tx = null;
    	for(int i=0;i<list.size();i++){
			List l = rkd.findByProperty("rokeKey", list.get(i));
			if(l.size()>0){
				rk = (RoKey)l.get(0);
				rqk = rqkd.findById(new RoQuestionKeyId(rk.getRokeId(),this.roquId));
				if(rqk != null){
					rqk.setRoqkCount(Long.valueOf(rqk.getRoqkCount().longValue() + 1));
					tx = rqkd.getSession().beginTransaction();
					rqkd.attachDirty(rqk);
					tx.commit();
					continue;
				}
			} else {
				rk = new RoKey();
				rk.setRokeKey((String)list.get(i));
				rk.setRokeCreateTime(new Date());
				tx = rkd.getSession().beginTransaction();
				rkd.save(rk);
				tx.commit();
			}
			rqk = new RoQuestionKey();
			rqk.setId(new RoQuestionKeyId(rk.getRokeId(),this.roquId));
			rqk.setRoqkCount(Long.valueOf(1));
			tx = rqkd.getSession().beginTransaction();
			rqkd.save(rqk);
			tx.commit();
		}
    }

}
